<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="process-device-container">
          <div class="page-header">
            <h2>为工序区分配设备</h2>
            <div class="header-actions">
              <el-button type="primary" @click="refreshData">
                <el-icon><Refresh /></el-icon> 刷新数据
              </el-button>
            </div>
          </div>

          <el-alert
            v-if="showDragTip"
            title="提示：勾选右侧设备后，可将设备拖拽到左侧工序区进行分配"
            type="info"
            :closable="false"
            show-icon
            style="margin-bottom: 20px"
          />

          <div class="panels-container">
            <!-- 左侧：可用工序区列表 -->
            <div class="process-panel">
              <div class="panel-header">
                <h3>可用工序区</h3>
                <el-input
                  v-model="processSearchKeyword"
                  placeholder="搜索工序区"
                  clearable
                  class="search-input"
                  @clear="handleProcessSearch"
                  @keyup.enter="handleProcessSearch"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon" @click="handleProcessSearch">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </div>
              <div class="panel-content" v-loading="processLoading">
                <div
                  v-if="filteredProcesses.length === 0"
                  class="empty-placeholder"
                >
                  暂无可用工序区
                </div>
                <div
                  v-for="process in filteredProcesses"
                  :key="process.taskId"
                  class="process-card"
                  :class="{ 'drop-target': isDropTarget(process.taskId) }"
                  :data-id="process.taskId"
                  @dragover.prevent="handleDragOver"
                  @dragleave.prevent="handleDragLeave"
                  @drop.prevent="handleDrop(process)"
                >
                  <div class="process-header">
                    <span class="process-number">工序区 #{{ process.taskId }}</span>
                    <el-tag :type="getStatusType(process.status)">{{ process.status }}</el-tag>
                  </div>
                  <div class="process-info">
                    <div class="info-item">
                      <span class="label">工序名称:</span>
                      <span class="value">{{ process.processName }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">产品型号:</span>
                      <span class="value">{{ process.productModel }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">所属产线:</span>
                      <span class="value">{{ process.lineId }}</span>
                    </div>
                    <div class="info-item">
                      <span class="label">创建时间:</span>
                      <span class="value">{{ formatDateTime(process.createdAt) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 右侧：空闲设备列表 -->
            <div class="equipment-panel">
              <div class="panel-header">
                <h3>空闲设备</h3>
                <el-input
                  v-model="equipmentSearchKeyword"
                  placeholder="搜索设备"
                  clearable
                  class="search-input"
                  @clear="handleEquipmentSearch"
                  @keyup.enter="handleEquipmentSearch"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon" @click="handleEquipmentSearch">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </div>
              <div class="panel-content" v-loading="equipmentLoading">
                <div
                  v-if="filteredEquipments.length === 0"
                  class="empty-placeholder"
                >
                  暂无空闲设备
                </div>
                <div class="equipment-list">
                  <div
                    v-for="equipment in filteredEquipments"
                    :key="equipment.equipmentId"
                    class="equipment-card"
                    :class="{ 'selected': equipment.selected }"
                    draggable="true"
                    @dragstart="handleDragStart(equipment, $event)"
                    @dragend="handleDragEnd"
                    @click="handleEquipmentSelect(equipment)"
                  >
                    <div class="equipment-header">
                      <span class="equipment-id">设备 #{{ equipment.equipmentId }}</span>
                      <el-checkbox v-model="equipment.selected" @click.stop></el-checkbox>
                    </div>
                    <div class="equipment-info">
                      <div class="info-item">
                        <span class="label">设备名称:</span>
                        <span class="value highlight">{{ equipment.name }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">设备类型:</span>
                        <span class="value">{{ equipment.type }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">设备状态:</span>
                        <span class="value">{{ equipment.status }}</span>
                      </div>
                      <div class="info-item">
                        <span class="label">温度信息:</span>
                        <div class="temp-info">
                          <span class="value">{{ equipment.currentTemp }}°C / {{ equipment.tempThreshold }}°C</span>
                          <el-progress
                            :percentage="getTempPercentage(equipment.currentTemp, equipment.tempThreshold)"
                            :status="getTempStatus(equipment.currentTemp, equipment.tempThreshold)"
                            :stroke-width="8"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分配确认对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="确认分配设备"
      width="30%"
    >
      <div class="assign-dialog-content">
        <p>您确定要将以下设备分配到工序区吗？</p>
        <div class="detail-item">
          <span class="label">设备ID:</span>
          <span class="value">{{ currentEquipment?.equipmentId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">设备名称:</span>
          <span class="value">{{ currentEquipment?.name }}</span>
        </div>
        <div class="detail-item">
          <span class="label">设备类型:</span>
          <span class="value">{{ currentEquipment?.type }}</span>
        </div>
        <div class="detail-item">
          <span class="label">工序名称:</span>
          <span class="value">{{ currentProcess?.processName }}</span>
        </div>
        <div class="detail-item">
          <span class="label">产品型号:</span>
          <span class="value">{{ currentProcess?.productModel }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAssign">确认分配</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import {getFreeEquipments, addEquipmentToProcessTask, availableProcessTask} from '@/api/production'

// 数据定义
const processes = ref([])
const equipments = ref([])
const processLoading = ref(false)
const equipmentLoading = ref(false)
const processSearchKeyword = ref('')
const equipmentSearchKeyword = ref('')
const showDragTip = ref(false)
const assignDialogVisible = ref(false)
const currentEquipment = ref(null)
const currentProcess = ref(null)
const dropTargetId = ref(null)
const draggedEquipment = ref(null)
const selectedEquipments = ref([])

// 过滤后的工序区列表
const filteredProcesses = computed(() => {
  if (!processSearchKeyword.value) return processes.value

  const keyword = processSearchKeyword.value.toLowerCase()
  return processes.value.filter(process =>
    process.taskId.toString().includes(keyword) ||
    process.processName.toLowerCase().includes(keyword) ||
    (process.productModel && process.productModel.toLowerCase().includes(keyword))
  )
})

// 过滤后的设备列表
const filteredEquipments = computed(() => {
  if (!equipmentSearchKeyword.value) return equipments.value

  const keyword = equipmentSearchKeyword.value.toLowerCase()
  return equipments.value.filter(equipment =>
    equipment.equipmentId.toString().includes(keyword) ||
    equipment.name.toLowerCase().includes(keyword) ||
    equipment.type.toLowerCase().includes(keyword)
  )
})

// 获取空闲设备列表
const fetchEquipments = async () => {
  equipmentLoading.value = true
  try {
    const res = await getFreeEquipments()
    if (res.success) {
      equipments.value = (res.data || []).map(item => ({
        ...item,
        selected: false
      }))
    } else {
      ElMessage.error(res.message || '获取空闲设备列表失败')
    }
  } catch (error) {
    ElMessage.error('获取空闲设备列表失败')
  } finally {
    equipmentLoading.value = false
  }
}

// 获取可用工序区列表
const fetchAvailableProcesses = async () => {
  processLoading.value = true
  try {
    // 如果有选中的设备，则获取该设备可用的工序区
    if (selectedEquipments.value.length > 0) {
      // 使用第一个选中的设备ID查询可用工序区
      const deviceId = selectedEquipments.value[0].equipmentId
      const res = await availableProcessTask({
          deviceId:deviceId
      })
      if (res.success) {
        processes.value = res.data || []
      } else {
        ElMessage.error(res.message || '获取可用工序区列表失败')
      }
    } else {
      processes.value = []
    }
  } catch (error) {
    ElMessage.error('获取可用工序区列表失败')
  } finally {
    processLoading.value = false
  }
}

// 设备选择处理
const handleEquipmentSelect = (equipment) => {
  equipment.selected = !equipment.selected
  if (equipment.selected) {
    selectedEquipments.value.push(equipment)
  } else {
    const index = selectedEquipments.value.findIndex(eq => eq.equipmentId === equipment.equipmentId)
    if (index !== -1) {
      selectedEquipments.value.splice(index, 1)
    }
  }

  if (selectedEquipments.value.length > 0) {
    fetchAvailableProcesses()
    showDragTip.value = true
  } else {
    processes.value = []
    showDragTip.value = false
  }
}

// 拖拽处理
const handleDragStart = (equipment, event) => {
  if (!equipment.selected) {
    // 如果拖拽的设备未被选中，先选中它
    equipment.selected = true
    handleEquipmentSelect(equipment)
  }

  draggedEquipment.value = equipment
  showDragTip.value = false
}

const handleDragEnd = () => {
  dropTargetId.value = null
}

const handleDragOver = (event) => {
  event.preventDefault()

  // 获取拖拽目标工序区
  const processCard = event.target.closest('.process-card')
  if (processCard) {
    const processId = processCard.dataset.id
    dropTargetId.value = processId
  }
}

const handleDragLeave = (event) => {
  // 确保不是子元素的dragleave事件
  if (!event.currentTarget.contains(event.relatedTarget)) {
    dropTargetId.value = null
  }
}

const handleDrop = (process) => {
  currentProcess.value = process
  currentEquipment.value = draggedEquipment.value
  assignDialogVisible.value = true
}

// 判断是否是当前拖拽目标
const isDropTarget = (taskId) => {
  return dropTargetId.value === taskId.toString()
}

// 确认分配
const confirmAssign = async () => {
  try {
    const res = await addEquipmentToProcessTask(
      currentEquipment.value.equipmentId,
      currentProcess.value.taskId
    )

    if (res.success) {
      ElMessage.success('设备分配成功')
      assignDialogVisible.value = false

      // 从列表中移除已分配的设备
      equipments.value = equipments.value.filter(e => e.equipmentId !== currentEquipment.value.equipmentId)
      selectedEquipments.value = selectedEquipments.value.filter(e => e.equipmentId !== currentEquipment.value.equipmentId)

      // 如果没有选中的设备了，清空工序区列表
      if (selectedEquipments.value.length === 0) {
        processes.value = []
      }
    } else {
      ElMessage.error(res.message || '设备分配失败')
    }
  } catch (error) {
    ElMessage.error('设备分配失败')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '生产中':
      return 'success'
    case '未开始':
      return 'info'
    case '已完成':
      return ''
    default:
      return 'info'
  }
}

// 获取温度百分比
const getTempPercentage = (current, threshold) => {
  if (!current || !threshold) return 0
  return Math.min(Math.round((current / threshold) * 100), 100)
}

// 获取温度状态
const getTempStatus = (current, threshold) => {
  if (!current || !threshold) return ''
  const percentage = (current / threshold) * 100
  if (percentage >= 90) return 'exception'
  if (percentage >= 70) return 'warning'
  return 'success'
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 刷新数据
const refreshData = () => {
  fetchEquipments()
  if (selectedEquipments.value.length > 0) {
    fetchAvailableProcesses()
  }
}

// 搜索处理
const handleProcessSearch = () => {
  // 过滤由计算属性处理
}

const handleEquipmentSearch = () => {
  // 过滤由计算属性处理
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEquipments()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.process-device-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.panels-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.process-panel,
.equipment-panel {
  flex: 1;
  background: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.panel-content {
  min-height: 400px;
}

.search-input {
  width: 200px;
}

.empty-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
}

.process-card {
  background: white;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.equipment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.equipment-card {
  cursor: pointer;
  width: calc(50% - 7.5px);
  background: white;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.equipment-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1);
}

.equipment-card.selected {
  border: 2px solid #409eff;
  background-color: rgba(64, 158, 255, 0.05);
}

.process-card.drop-target {
  border: 2px dashed #409eff;
  background-color: rgba(64, 158, 255, 0.1);
}

.process-header,
.equipment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.process-number,
.equipment-id {
  font-weight: bold;
  font-size: 15px;
}

.process-info,
.equipment-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #606266;
  margin-right: 8px;
  min-width: 70px;
}

.value {
  color: #303133;
}

.value.highlight {
  font-weight: bold;
  color: #409eff;
}

.temp-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  width: 100%;
}

.assign-dialog-content {
  padding: 10px 0;
}

.detail-item {
  margin: 10px 0;
  display: flex;
}

.detail-item .label {
  font-weight: bold;
  width: 80px;
}
</style>
